package org.pettyfox.test.utils.dbpress.service;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.pettyfox.test.utils.dbpress.modules.biz.Table1Biz;
import org.pettyfox.test.utils.dbpress.modules.po.Table1;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 *     
 * 批量保存服务
 * @author pettyfox.top  
 * @version V1.0   
 * @date 2020-06-12
 */
@Service
@Slf4j
public class BatchSaveService {
    @Resource
    private Table1Biz table1Biz;
    @Scheduled(fixedDelay = 10000)
    public void monitor(){

    }
    public void startDbPress(int threadCount,int rowCount,int rowSize,int batchSize){
        Table1 row = buildRow(rowSize);
        CountDownLatch latch = new CountDownLatch(threadCount);
        new Thread(()->{
            table1Biz.save(row);
        }).start();
        table1Biz.save(row);
    }
    public void startDbPress(int count,int rowSize,int batchSize){
        Table1 row = buildRow(rowSize);
        List<Table1> batch = new ArrayList<>();
        for(int i = 0;i<batchSize;i++){
            batch.add(row);
        }
        long startTime = System.currentTimeMillis();
        int rowCount = 0;
        for(int i = 0;i<count;i++){
            while(true){
                long ctime = System.currentTimeMillis();
                if(ctime - startTime < 1000){
                    if(batchSize == 1){
                        table1Biz.save(row);
                    }else{
                        table1Biz.saveBatch(batch,1000);
                    }
                    rowCount+=batchSize;
                }else{
                    log.info("size:{}byte,iops:{}/{}ms",rowSize,rowCount,(ctime-startTime));
                    startTime = ctime;
                    rowCount = 0;
                    break;
                }
            }
        }
        table1Biz.save(row);
    }
    public Table1 buildRow(int rowSize){
        JSONObject object = new JSONObject();
        if(rowSize<14){
            object.put("c1","aaaaaaaaaaaaaa");
        }else{
            int cells = rowSize/14;
            for(int i = 1;i<14;i++){
                StringBuffer sb = new StringBuffer();
                for(int j = 0;j<cells;j++){
                    sb.append("a");
                    object.put("c"+i,sb.toString());
                }
            }
        }

        return object.toJavaObject(Table1.class);

    }
}
